package com.lixin.smartclassroom.app

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.core.content.ContextCompat
import com.drake.channel.sendTag
import com.drake.logcat.LogCat
import com.drake.net.utils.TipUtils.toast
import com.lixin.smartclassroom.SmartClassroomApp
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.utils.TestImageLoader
import com.lixinkeji.api.JsonHttpConverter
import com.lixinkeji.api.NetHttp
import com.lixinkeji.extension.isLogin
import com.lixinkeji.extension.token
import com.previewlibrary.ZoomMediaLoader
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.io.File

/**
 * Description
 * Author: lwc
 * Date:2023/11/1 14:49
 */
object App {

    const val HOST_IMG = "http://api.huobancommunity.com"

    const val HOST = "http://121.41.179.145/lixin"

    lateinit var wxApi: IWXAPI

    //    const val HOST = "http://122.114.173.136:8893"
    const val API = "$HOST/api/"
    private val context: Context by lazy { SmartClassroomApp.getInstants() }

    /**
     * 人脸识别图片保存的路径
     * @return String
     */
    fun getFaceImageFilePath(): String {
        val path = "${context.externalCacheDir!!.absolutePath}/FaceImage/"
        val file = File(path)
        if (!file.exists()) {
            file.mkdir()
        }
        return path
    }

    /**
     * 视频录制保存的路径
     * @return String
     */
    fun getVideoFilePath(): String {
        val path = "${context.getExternalFilesDir(null)!!.absolutePath}/Video/"
        val file = File(path)
        if (!file.exists()) {
            file.mkdir()
        }
        return path
    }

    /**
     * 录音保存路径
     * @return String
     */
    fun getVoiceFilePath(): String {
        val path = "${context.getExternalFilesDir(null)!!.absolutePath}/Voice/"
        val file = File(path)
        if (!file.exists()) {
            file.mkdir()
        }
        return path
    }

    /**
     * 音乐下载路径
     * @return String
     */
    fun getMusicDownloadPath(): String {
        val path = "${context.getExternalFilesDir(null)!!.absolutePath}/Music/"
        val file = File(path)
        if (!file.exists()) {
            file.mkdir()
        }
        return path
    }


    fun init(context: Context) {
        //音视频合成debug开关日志
//        RxFFmpegInvoke.getInstance().setDebug(true)
//        BRV.modelId = BR.data
        initLogCat()
        initNetHttp()
        //路由初始化
        // 这两行必须写在init之前，否则这些配置在init过程中将无效
//        ARouter.openLog()// 打印日志
//        ARouter.openDebug()// 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
//        ARouter.init(HuoBanApp.getInstants())// 尽可能早，推荐在Application中初始化
//        if (context.isAgree) initSdk()
        ZoomMediaLoader.getInstance().init(TestImageLoader())
    }

    fun initSdk() {
        if (SmartClassroomApp.instance.isLogin)
            initTPNS()

        initWx()
//        initRongCloud(AgencyReceiptApp.getInstants())

    }

    fun initTPNS() {

    }

    private fun initWx() {
        // APP_ID 替换为你的应用从官方网站申请到的合法appID
// IWXAPI 是第三方app和微信通信的openApi接口

// 通过WXAPIFactory工厂，获取IWXAPI的实例
        wxApi = WXAPIFactory.createWXAPI(SmartClassroomApp.getInstants(), Sdk.WX_APPID, true);

        // 将应用的appId注册到微信
        wxApi.registerApp(Sdk.WX_APPID);

        //建议动态监听微信启动广播进行注册到微信
        ContextCompat.registerReceiver(
            SmartClassroomApp.getInstants(),
            object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    // 将该app注册到微信
                    wxApi.registerApp(Sdk.WX_APPID);
                }

            },
            IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP),
            ContextCompat.RECEIVER_VISIBLE_TO_INSTANT_APPS
        )
    }

    /**
     * 初始化网络请求，全局配置
     */
    private fun initNetHttp() {
        NetHttp.init(
            context, API, JsonHttpConverter(),
            block = {
                //全局请求头/参数
                addHeader("Content-Type", "application/json")
//                    addHeader("Accept-Encoding","identity")
                addHeader("apptoken", SmartClassroomApp.getInstants().token)

            }, error = {
                toast(it.message)
                when (it.code) {
                    102 -> {
                        //token失效
                        sendTag("HttpLogout")
                    }
                }
            })
    }

//    private val unreadListener: V2TIMConversationListener = object : V2TIMConversationListener() {
//        override fun onTotalUnreadMessageCountChanged(totalUnreadCount: Long) {
//            //todo 暂未接入华为推送
//            if (!BrandUtil.isBrandHuawei()) {
//                return
//            }
//            LogCat.e("huawei badge = ${totalUnreadCount.toInt()}")
//            try {
//                val extra = Bundle()
//                extra.putString("package", context.packageName)
//                extra.putString("class", "com.lalifa.qichen.ui.SplashActivity")
//                extra.putInt("badgenumber", totalUnreadCount.toInt())
//                context.contentResolver.call(
//                    Uri.parse("content://com.huawei.android.launcher.settings/badge/"),
//                    "change_badge",
//                    null,
//                    extra
//                )
//            } catch (e: Exception) {
//                LogCat.e("huawei badge exception: " + e.localizedMessage)
//            }
//        }
//    }

    private fun initLogCat() {
        LogCat.apply {
            tag = SmartClassroomApp.getInstants().resources.getString(R.string.app_name)
//            enabled = BuildConfig.DEBUG
        }
    }


    /**
     * 初始化融云
     * @param context Context
     */
//    private fun initRongCloud(context: Context) {
//
//        val config = PushConfig.Builder()
//            .enableRongPush(true)
////            .enableMiPush(Sdk.miPushAppId, Sdk.miPushAppKey)
////            .enableOppoPush(Sdk.oppoAppKey, Sdk.oppoAppSecret)
////            .enableHWPush(true)
////            .enableVivoPush(true)
//            .build()
//        RongPushClient.setPushConfig(config)
//
//        RongIM.init(AgencyReceiptApp.getInstants(), Sdk.rongCloudAppId, true)
//
//        /** 是否震动 */
//        RongConfigCenter.featureConfig().isVibrateInForeground = true
//        /** 是否有铃声 */
//        RongConfigCenter.featureConfig().isSoundInForeground = true
//
//
//        //添加模板
//
//        val myMessages = ArrayList<Class<out MessageContent?>>()
//        myMessages.add(CroppingOrderMessage::class.java)
//        myMessages.add(OrderMessage::class.java)
//        RongIMClient.registerMessageType(myMessages)
//        RongConfigCenter.conversationConfig().addMessageProvider(CroppingOrderProvider())
//        RongConfigCenter.conversationConfig().addMessageProvider(OrderProvider())
//
////        RongIM.getInstance().registerConversationTemplate(CustomConversationProvider())
//
//
////        RongConfigCenter.notificationConfig().setInterceptor(object :NotificationConfig.Interceptor{
////            override fun isNotificationIntercepted(message: Message?): Boolean {
////                rxManager.post("refreshMessage", "cs")
////                return true
////            }
////
////            override fun onPendingIntent(
////                pendingIntent: PendingIntent?,
////                intent: Intent?
////            ): PendingIntent {
////                TODO("Not yet implemented")
////            }
////
////            override fun isHighPriorityMessage(message: Message?): Boolean {
////                TODO("Not yet implemented")
////            }
////
////            override fun onRegisterChannel(defaultChannel: NotificationChannel?): NotificationChannel {
////                TODO("Not yet implemented")
////            }
////
////        })
//
//
////        RongIM.registerMessageTemplate(MyTextMessageItemProvider())
////        RongConfigCenter.conversationConfig().replaceMessageProvider(
////            TextMessageItemProvider().javaClass,
////            MyTextMessageItemProvider()
////        )
////        RongIM.registerMessageTemplate(MyLocationMessageItemProvider())
////        RongConfigCenter.conversationConfig().replaceMessageProvider(
////            LocationMessageItemProvider().javaClass,
////            MyLocationMessageItemProvider()
////        )
////        RongIM.registerMessageTemplate(MyVoiceMessageItemProvider())
////        RongConfigCenter.conversationConfig().replaceMessageProvider(
////            VoiceMessageItemProvider().javaClass,
////            MyVoiceMessageItemProvider()
////        )
////
////        RongIM.registerMessageTemplate(MyHQVoiceMessageItemProvider())
////        RongConfigCenter.conversationConfig().replaceMessageProvider(
////            HQVoiceMessageItemProvider().javaClass,
////            MyHQVoiceMessageItemProvider()
////        )
////
////        RongIM.registerMessageTemplate(MyImageMessageItemProvider())
////        RongConfigCenter.conversationConfig().replaceMessageProvider(
////            ImageMessageItemProvider().javaClass,
////            MyImageMessageItemProvider()
////        )
////
////        RongIM.registerMessageTemplate(MyCallEndMessageItemProvider())
////
////        RongConfigCenter.conversationConfig().replaceMessageProvider(
////            CallEndMessageItemProvider().javaClass,
////            MyCallEndMessageItemProvider()
////        )
////
////        RongConfigCenter.featureConfig().isSoundInForeground = true
////        RongConfigCenter.featureConfig().isVibrateInForeground = true
////
//
//        //注册自定义会话列表
//        RouteUtils.registerActivity(
//            RouteUtils.RongActivityType.ConversationListActivity,
//            MainActivity::class.java
//        )
//
//        //注册自定义会话界面
//        RouteUtils.registerActivity(
//            RouteUtils.RongActivityType.ConversationActivity,
//            MyRongConversationActivity::class.java
//        )
//        RongConfigCenter.featureConfig().kitImageEngine = object : GlideKitImageEngine() {
//            override fun loadConversationPortrait(
//                context: Context,
//                url: String,
//                imageView: ImageView,
//                message: Message?
//            ) {
//                //设置会话页面的头像加载
//                imageView.loadCircle(url, R.mipmap.def_head)
//            }
//
//            override fun loadConversationListPortrait(
//                context: Context,
//                url: String,
//                imageView: ImageView,
//                conversation: Conversation?
//            ) {
//                //设置会话列表的头像加载
//                imageView.loadCircle(url, R.mipmap.def_head)
//            }
//        }
////        //注册小视频
////        RongExtensionManager.getInstance().registerExtensionModule(VideoPlugin())
////        //会话页面-》加号区域自定义//
////        RongExtensionManager.getInstance().registerExtensionModule(MyDefaultLocationPlugin())
//
//
////        RongExtensionManager.getInstance().extensionConfig = object : DefaultExtensionConfig() {
////            @SuppressLint("UseCompatLoadingForDrawables")
////            override fun getPluginModules(
////                conversationType: Conversation.ConversationType?,
////                targetId: String?
////            ): MutableList<IPluginModule> {
////                val list = arrayListOf<IPluginModule>()
////                list.add(object : MyImagePlugin() {
////                    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
////                    override fun obtainDrawable(context: Context?): Drawable {
////                        return context?.getDrawable(R.drawable.chat_pic)!!
////                    }
////                })
////                list.add(object : TakePhotoPlugin() {
////                    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
////                    override fun obtainDrawable(context: Context?): Drawable {
////                        return context?.getDrawable(R.drawable.chat_shot)!!
////                    }
////
////                    override fun obtainTitle(context: Context?): String {
////                        return context?.getString(R.string.shot)!!
////                    }
////
////                })
////                list.add(object : MyAudioPlugin() {
////                    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
////                    override fun obtainDrawable(context: Context?): Drawable {
////                        return context?.getDrawable(R.drawable.chat_voice)!!
////                    }
////                })
////                list.add(object : MyDefaultLocationPlugin() {
////                    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
////                    override fun obtainDrawable(context: Context?): Drawable {
////                        return context?.getDrawable(R.drawable.chat_location)!!
////                    }
////                })
//
//
////                return list
////            }
////        }
//        //连接状态
//        RongIM.setConnectionStatusListener { status ->
//            LogCat.e("融云链接状态 $status")
//            AgencyReceiptApp.getInstants().im_isLogin =
//                status != RongIMClient.ConnectionStatusListener.ConnectionStatus.UNCONNECTED
//            sendEvent(status, "IMConnectState")
//        }
//
//        IMCenter.getInstance()
//            .addOnReceiveMessageListener(object : RongIMClient.OnReceiveMessageWrapperListener() {
//                override fun onReceived(
//                    message: Message?,
//                    left: Int,
//                    hasPackage: Boolean,
//                    offline: Boolean
//                ): Boolean {
//                    sendEvent("cs", "refreshUnreadMessageCount")
//                    return true
//                }
//
//            });
//
////        RongIM.getInstance().addUnReadMessageCountChangedObserver({ sendEvent("cs", "refreshUnreadMessageCount") }, Conversation.ConversationType.PRIVATE);
//
//        var conversationTypes = arrayOf(Conversation.ConversationType.PRIVATE)
//        UnReadMessageManager.getInstance().addObserver(conversationTypes) {
//            sendEvent(
//                "cs",
//                "refreshUnreadMessageCount"
//            )
//        }
//    }
}